package com.slfx.zookeeper.idgen.demo.sequence;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created by sunyujia@aliyun.com on 2016/2/25.
 */
@Component
public class ZkVersionDistributedSequence implements DistributedSequence {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(ZkVersionDistributedSequence.class);

    @Resource
    private CuratorFramework client;

    /**
     * 提升性能：不需要每次都要判断这个根节点是否存在
     */
    private volatile boolean initFlag;

    public Long sequence(String sequenceName) {
        try {
            //判断节点是否存在，如果不存在，则创建节点
            if (!initFlag) {
                Stat stat = client.checkExists().forPath("/" + sequenceName);
                if (stat == null) {
                    String s = client.create().withMode(CreateMode.PERSISTENT).forPath("/" + sequenceName);
                }
                initFlag = true;
            }
            int value = client.setData().withVersion(-1).forPath("/" + sequenceName, "".getBytes()).getVersion();
            return new Long(value);
        } catch (Exception e) {
            log.error("e:{}", e);
        }
        return null;
    }
}